/**
 * Copyright(c) kyle.
 */
package org.example.metrics;

import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricRegistry;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

import static java.util.concurrent.ThreadLocalRandom.current;

/**
 * SimpleGauge是最简单的自定义观测
 *
 * @author kyle
 * @version 1.00.00
 * @updateUser [Kyle]
 * @updateRemark [说明本次修改内容]
 * @date [2021-09-21 12:51]
 * @since [2021-09-21 12:51]
 */
public class SimpleGaugeExample {
    public static final MetricRegistry registry = new MetricRegistry();
    public static final //定义运行的相关参数
            ConsoleReporter reporter = ConsoleReporter.forRegistry(registry)
            .convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.SECONDS)
            .build();

    public static final BlockingDeque<Long> queue = new LinkedBlockingDeque<>(1_00);

    public static void main(String[] args) {
        Metric register = registry.<Gauge<Integer>>register(MetricRegistry.name(SimpleGaugeExample.class, "queue-size"),
                queue::size);

        reporter.start(1, TimeUnit.SECONDS);
        new Thread(()->{
            while (true){
                randomSleep();
                queue.add(System.nanoTime());
            }
        }).start();
        new Thread(()->{
            while (true){
                randomSleep();
                queue.poll();
            }
        }).start();
    }

    private static void randomSleep() {
        try {
            TimeUnit.SECONDS.sleep(current().nextInt(6));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
